package model

import (
	"github.com/go-ego/riot/types"
	"github.com/jinzhu/gorm"
	"maki/search"
)

// Article model.
type Article struct {
	Model

	Title        string    `gorm:"size:128" json:"title" validate:"required"`
	Content      string    `gorm:"type:text" json:"content" validate:"required"`
	Commentable  bool      `gorm:"default:true" json:"commentable"`
	CommentCount int       `json:"commentCount" validate:"-"`
	IP           string    `gorm:"size:128" json:"ip,omitempty" validate:"-"`
	UserAgent    string    `gorm:"size:255" json:"userAgent,omitempty" validate:"-"`
	Topped       bool      `json:"topped"`
	ViewCount    int       `json:"viewCount" validate:"-"`
	User         User      `json:"user" validate:"-"`
	UserID       uint64    `json:"userID" validate:"-"`
	Visible      bool      `gorm:"default:true" json:"visible"`
	Tags         []Tag     `gorm:"many2many:article_tag;" json:"tags" validate:"required"`
	Comments     []Comment `json:"comments" validate:"-"`
}

func (article *Article) AfterSave(scope *gorm.Scope) error {
	search.Engine.RemoveDoc(article.ID, true)
	var tags []string
	for _, tag := range article.Tags {
		tags = append(tags, tag.Name)
	}
	search.Engine.IndexDoc(article.ID, types.DocData{
		Content: article.Title + article.Content,
		Labels:  tags,
	})
	search.Engine.Flush()
	return nil
}

func (article *Article) AfterDelete(tx *gorm.DB) error {
	search.RemoveDoc(article.ID)
	search.Engine.Flush()
	return nil
}

// Abstract     string `gorm:"type:mediumtext" json:"a"`

func CreateSampleArticle() *Article {
	user := CreateSampleUser("test", "test123")
	article := Article{
		Title:   "test title",
		Content: "test content",
		UserID:  user.ID,
	}
	if status := DB.FirstOrCreate(&article); status.Error != nil {
		panic(status.Error)
	}
	return &article
}
